﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using CNCSoft.EWinform;
using CNCSoft.EWinform.ControlUtils;
using CNCSoft.EWinform.ERPApps;
using CNCSoft.EWinform.AGrid;
using CNCSoft.EData;

using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using System.Web.Mail;
using System.Data.SqlClient;

using System.Threading;
using System.Globalization;

using Common;

namespace CNCSoft.ErpApps.TMS
{
    public partial class frmBaoCaoKeToan : Form
    {

        public frmBaoCaoKeToan()
        {
            InitializeComponent();
        }

        public string _strReportCode = "";
        public string _strReportTitle = "";
        public string _strReportFile = "";

        public bool HaveGroup = false;
        public bool HaveParameterGroup = false;

        public frmBaoCaoKeToan(string strReportCode)
        {
            // Sets the UI culture to VietNamese (VietNam) / English
            if (GlobalVariable.WSInfo.Language == "Tiếng Việt")
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("vi-VN");
            else if (GlobalVariable.WSInfo.Language == "English")
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");

            InitializeComponent();

            _strReportCode = strReportCode;
            //Lay report title, report file name
            SqlDataReader DR = SQLHelper.ExecuteReader(GlobalVariable.WSInfo.ConnectionString,
                                                      "SELECT * FROM RP_LSTREPORT WHERE ReportCode = '" + _strReportCode + "'");
            while (DR.Read())
            {
                try
                {
                    _strReportTitle =   DR["ReportTitle"].ToString();
                    _strReportFile = Application.StartupPath + "\\Report\\" +  DR["ReportFileName"].ToString();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            try
            {
                txtTuNgay.Text = DateTime.Now.Date.AddDays(-DateTime.Now.Date.Day + 1).ToString("dd/MM/yyyy");
                txtDenNgay.Text = GlobalVariable.WSInfo.WorkingDate.ToString("dd/MM/yyyy");

                if (_strReportFile.ToLower().IndexOf(".rpt") < 0)
                    _strReportFile = _strReportFile + ".rpt";
                
                rpt.Load(_strReportFile);
                PublicFunction.SetDBLogonForReport(rpt);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        /*
        public frmBaoCaoKeToan(string strReportTitle, string strReportFile)
        {
            InitializeComponent();
            _strReportFile = strReportFile;
            _strReportTitle = strReportTitle;
            txtTuNgay.Text = DateTime.Now.Date.AddDays(-DateTime.Now.Date.Day + 1).ToString("dd/MM/yyyy");
            txtDenNgay.Text = GlobalVariable.WSInfo.WorkingDate.ToString("dd/MM/yyyy");

            rpt.Load(_strReportFile);
            PublicFunction.SetDBLogonForReport(rpt);

        }

        public frmBaoCaoKeToan(string strReportTitle, string strReportFile, DateTime pTuNgay, DateTime pDenNgay)
        {
            InitializeComponent();
            _strReportFile = strReportFile;
            _strReportTitle = strReportTitle;
            txtTuNgay.Text = pTuNgay.ToString("dd/MM/yyyy")  ;
            txtDenNgay.Text = pDenNgay.ToString("dd/MM/yyyy");

            rpt.Load(_strReportFile);
            
            PublicFunction.SetDBLogonForReport(rpt);

            foreach (ReportDocument subReport in rpt.Subreports)
            {
                PublicFunction.SetDBLogonForReport(subReport);
            }

        }
        */

        int intSoNgayDuocXem = 0;
        //Phan quyen xem so lieu theo ngay (So ngay duoc xem)
        private void PhanQuyenReport()
        {
            //string strReportCode = strReportFile.Replace(Application.StartupPath + "\\Report\\", "").Replace(".rpt", "");

            try
            {
                intSoNgayDuocXem = Convert.ToInt16(SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString, "SELECT SoNgayDuocXem FROM RP_LSTREPORT WHERE REPORTFILENAME = '" + _strReportCode + "' " +
                                                        "AND charindex('" + GlobalVariable.WSInfo.UserID + "', DanhSachUserID) > 0  "));
            } catch {};

            if (intSoNgayDuocXem > 0)
            {
                //MessageBox.Show(intSoNgayDuocXem.ToString());
                txtDenNgay.Text = txtTuNgay.getDateValue().AddDays(intSoNgayDuocXem - 1).ToString("dd/MM/yyyy");
                txtDenNgay.Enabled = false;
            }
        }


        private void frmBaoCaoKeToan_Load(object sender, EventArgs e)
        {
            this.Text = _strReportTitle;
            try
            {
                cmdInNguyenlop.Visible = (_strReportTitle.IndexOf("Report_Giaovu_PhieuDiemCaNhan") > 0);

                //Lop theo don vi (Shool/English/Aptech/...)
                //MessageBox.Show(GlobalVariable.WSInfo.CompanyID.ToLower());
                if (GlobalVariable.WSInfo.CompanyID.ToLower() == "school")
                {
                    txtMaLop.RefTable = "(SELECT * FROM DM_LOP) as DM_LOP";
                    txtMaLop.RefField = "MaLop";
                }
                else
                {
                    txtMaLop.RefTable = "(SELECT * FROM DM_KHOAHOC) as DM_KHOAHOC";
                    txtMaLop.RefField = "MaKhoaHoc";
                }

                //Kiem tra tham so cua report, neu ko co thi disable control truyen tham so tuong ung
                XacDinhThamSoVaGanGiaTriDefault();
                
                PhanQuyenReport();

                //Gan danh sach field report dong vao combobox tuong ung voi tung report
                if (HaveGroup)
                    SetComboDynamicGroup();

                cmdXem_Click(sender, e);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void XacDinhThamSoVaGanGiaTriDefault()
        {
            //Co so (User thoc Co so nao chi co quyen check/uncheck co so do   (nguoi nao de NULL xem nhu *  - VIP)
            string strCoSoOfUser = (SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                            "select isnull(Position, '*') from SYS_List_User where UserID='" + GlobalVariable.WSInfo.UserID + "'")).ToString().Replace("CS", "");
            chkCS1.Checked = false; chkCS1.Enabled = false;
            chkCS2.Checked = false; chkCS2.Enabled = false;
            if (strCoSoOfUser == "1")
            {
                chkCS1.Enabled = true;
                chkCS1.Checked = true;
            }
            if (strCoSoOfUser == "2")
            {
                chkCS2.Enabled = true;
                chkCS2.Checked = true;
            }
            //Xem duoc tat ca (VIP)
            if (strCoSoOfUser == "*")
            {
                chkCS1.Enabled = true; chkCS2.Enabled = true;
                chkCS1.Checked = true; chkCS2.Checked = true;
            }

            //Nien hoc
            txtMaNienHoc.Enabled = false;
            ParameterField pfMaNienHoc = rpt.ParameterFields.Find("@pMaNienHoc", "");
            if (pfMaNienHoc != null)
            {
                txtMaNienHoc.Enabled = true;
                txtMaNienHoc.Text = GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault");
            }

            //Hoc ky
            ParameterField pfMaHocKy = rpt.ParameterFields.Find("@pMaHocKy", "");
            chkHK1.Enabled = (pfMaHocKy != null); chkHK2.Enabled = (pfMaHocKy != null);

            //Hoc sinh (ma hoc tap)
            ParameterField pfMaHocTap = rpt.ParameterFields.Find("@pMaHocTap", "");
            ParameterField pfEnquiryNumber = rpt.ParameterFields.Find("@pEnquiryNumber", "");
            txtEnquiryNumber.Enabled = (pfMaHocTap != null || pfEnquiryNumber != null);

            //Lop
            ParameterField pfLop = rpt.ParameterFields.Find("@pMaLop", "");
            txtMaLop.Enabled = (pfLop != null || pfMaHocTap != null || pfEnquiryNumber != null);

            //Mon hoc
            ParameterField pfMon = rpt.ParameterFields.Find("@pMaMonKiemTra", "");
            txtMaMonKiemTra.Enabled = (pfMon != null);

            //Diem KT
            ParameterField pfCotDiemThongKe = rpt.ParameterFields.Find("@pCotDiemThongKe", "");
            if (pfCotDiemThongKe != null)
            { cboCotDiemThongke.Enabled = true; cboCotDiemThongke.SelectedIndex = 0; }
            else
            { cboCotDiemThongke.Enabled = false; cboCotDiemThongke.SelectedIndex = -1; }

            //Tu ngay den ngay
            ParameterField pfTuNgay = rpt.ParameterFields.Find("@pTuNgay", "");
            txtTuNgay.Text = ""; txtDenNgay.Text = ""; txtTuNgay.Enabled = false; txtDenNgay.Enabled = false;
            if (pfTuNgay != null)
            {
                txtTuNgay.Enabled  = true ;
                txtTuNgay.Text = txtTuNgay.Text = DateTime.Now.Date.AddDays(-DateTime.Now.Date.Day + 1).ToString("dd/MM/yyyy");
            }
            ParameterField pfDenNgay = rpt.ParameterFields.Find("@pDenNgay", "");
            if (pfDenNgay != null)
            {
                txtDenNgay.Enabled = true;
                txtDenNgay.Text = GlobalVariable.WSInfo.WorkingDate.ToString("dd/MM/yyyy"); 
            }

            //Tai khoan / Ngan hang
            ParameterField pfTK = rpt.ParameterFields.Find("@pTaiKhoan", "");
            ParameterField pfNH = rpt.ParameterFields.Find("@pNganHang", "");
            //Set datasource cho CboTaiKhoan (hoac DM_TaiKHOAN hoac DM_NGANHANG)
            if (pfNH != null)
            {
                lblTaiKhoan.Text = "Ngân hàng";
                DataTable dtNH = new DataTable();
                SQLHelper.Fill(dtNH, GlobalVariable.WSInfo.ConnectionString, "SELECT * FROM DM_NGANHANG");
                cboTaiKhoan.DataSource = dtNH;
                cboTaiKhoan.DisplayMember = "TenNganHang";
                cboTaiKhoan.ValueMember = "MaNganHang";
            }
            else
            {
                lblTaiKhoan.Text = "Tài khoản";
                DataTable dtTK = new DataTable();
                SQLHelper.Fill(dtTK, GlobalVariable.WSInfo.ConnectionString, "SELECT * FROM DM_TAIKHOAN");
                cboTaiKhoan.DataSource = dtTK;
                cboTaiKhoan.DisplayMember = "TenTaiKhoanVN";
                cboTaiKhoan.ValueMember = "MaTaiKhoan";
                cboTaiKhoan.SelectedValue = "1111";
            }
            panelTaiKhoan.Visible = (pfTK != null || pfNH != null);

            //Group panel
            //Gan danh sach field report dong vao combobox tuong ung voi tung report
            SetComboDynamicGroup();
        }


        //Load report
        ReportDocument rpt = new ReportDocument();


        private void cmdXem_Click(object sender, EventArgs e)
        {
            cmdXem.Enabled = false;
            try
            {
                //Set parameter
                GanGiaTriChoCacKieuThamSo();

                //Gan report source
                CRViewer.ReportSource = rpt;

            }
            catch (Exception ex)
            {
                cmdXem.Enabled = true;
                MessageBox.Show(ex.Message, "cmdXem error!");
            }
            cmdXem.Enabled = true;
        }

        private void GanGiaTriChoCacKieuThamSo()
        {
            //Cac tham so chung
            PublicFunction.SetParameter(rpt, "@pTuNgay", txtTuNgay.getDateValue());
            PublicFunction.SetParameter(rpt, "@pDenNgay", txtDenNgay.getDateValue());
            PublicFunction.SetParameter(rpt, "pThoiGian", ReportUtilities.ReportUtilities.ThoiGianDep(txtTuNgay.getDateValue(), txtDenNgay.getDateValue()));
            PublicFunction.SetParameter(rpt, "pMoRongDong", chkMoRongDong.Checked);

            //Cac tham so chuyen mon
            PublicFunction.SetParameter(rpt, "@pCS1", chkCS1.Checked);
            PublicFunction.SetParameter(rpt, "@pCS2", chkCS2.Checked);
            PublicFunction.SetParameter(rpt, "@pMaNienHoc", txtMaNienHoc.Text);
            PublicFunction.SetParameter(rpt, "@pMaHocKy", "");
            if (chkHK1.Checked)
                PublicFunction.SetParameter(rpt, "@pMaHocKy", "1");
            if (chkHK2.Checked)
                PublicFunction.SetParameter(rpt, "@pMaHocKy", "2");
            if (chkHK1.Checked && chkHK2.Checked)
                PublicFunction.SetParameter(rpt, "@pMaHocKy", "CN");  //Ca Nam
            PublicFunction.SetParameter(rpt, "@pMaLop", txtMaLop.Text);
            PublicFunction.SetParameter(rpt, "@pMaHocTap", txtEnquiryNumber.Text);   //for school
            PublicFunction.SetParameter(rpt, "@pEnquiryNumber", txtEnquiryNumber.Text);  //for none scholl
            PublicFunction.SetParameter(rpt, "@pMaMonKiemTra", txtMaMonKiemTra.Text);
            PublicFunction.SetParameter(rpt, "@pCotDiemThongKe", cboCotDiemThongke.Text);
            
            //PublicFunction.SetParameter(rpt, "@pDanhHieuThiDua", strMaMonKiemTra);  // Muon bien strMaMonKiemTra lam de gan dau vao khi goi form cho tham so DHTD

            PublicFunction.SetParameter(rpt, "pGVCN", " ");
            try
            {
                PublicFunction.SetParameter(rpt, "pGVCN", SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString,
                    "SELECT TenGiaoVien FROM DM_LOP join DM_GIAOVIEN on DM_LOP.MaGiaoVien = DM_GIAOVIEN.MaGiaoVien where MaLop = '" + txtMaLop.Text + "'"));
            } catch {};
            //PublicFunction.SetParameter(rpt, "pAcademicHead", GlobalVariable.WSInfo["Sys.UserName.AcademicHead"]);

            //Tham so cho 2 ma nien hoc
            ParameterField pfMaNienHoc_CuMoi = rpt.ParameterFields.Find("@pMaNienHocCu", "");
            if (pfMaNienHoc_CuMoi != null)
            {
                PublicFunction.SetParameter(rpt, "@pMaNienHocCu", GlobalVariable.WSInfo.getAppProperty("MaNienHocDefault"));
                PublicFunction.SetParameter(rpt, "@pMaNienHocMoi", GlobalVariable.WSInfo.getAppProperty("MaNienHocMoi"));
            }

            //Cac tham so string
            PublicFunction.SetParameter(rpt, "pAcademicHead", GlobalVariable.WSInfo.getAppProperty("Sys.UserName.AcademicHead", ""));

            //Xac dinh parameter cua group
            if (cboFieldNameGroup.SelectedIndex != -1)
            {
                string strFieldName = ((DataRowView)cboFieldNameGroup.Items[cboFieldNameGroup.SelectedIndex])["GroupFieldDynamic"].ToString();
                string strGroupName = ((DataRowView)cboFieldNameGroup.Items[cboFieldNameGroup.SelectedIndex])["GroupFieldName"].ToString();
                PublicFunction.SetParameter(rpt, "@pFieldGroup", strFieldName);
                PublicFunction.SetParameter(rpt, "@pFieldGroupName", strGroupName);
            }
            else
            {
                PublicFunction.SetParameter(rpt, "@pFieldGroup", "");
                PublicFunction.SetParameter(rpt, "@pFieldGroupName", "");
            }
        }


        private void SetComboDynamicGroup()
        {
            panelGroup.Visible = false;
            try
            {
                DataTable db = new DataTable("TBGropup");
                string strReportFileNoPath = _strReportFile.Replace(Application.StartupPath + "\\Report\\", "").Replace(".rpt","") ;
                SQLHelper.Fill(db, GlobalVariable.WSInfo.ConnectionString, "SELECT * FROM RP_LSTREPORT_DYNAMICGROUP WHERE ReportFileName = '" + strReportFileNoPath + "'");
                if (db.Rows.Count > 0)
                {
                    this.cboFieldNameGroup.DataSource = db;
                    this.cboFieldNameGroup.DisplayMember = "Description";
                    this.cboFieldNameGroup.ValueMember = "GroupFieldDynamic";
                    cboFieldNameGroup.SelectedIndex = 0;
                    panelGroup.Visible = true;
                }
            }
            catch (Exception ex)
            {
                panelGroup.Visible = true;
                MessageBox.Show(ex.Message, "SetComboDynamicGroup");
            }
        }

        private void chkMoRongDong_CheckedChanged(object sender, EventArgs e)
        {
            cmdXem_Click(cmdXem, e);
        }

        
        
        private void cboFieldNameGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            cmdXem_Click(cmdXem, e);
        }


        string pdfFile = "";

        
        private void sendmail()
        {
            try
            {
                string strEmailAddressTo = GlobalVariable.WSInfo.getAppProperty("Sys.UserName.GiamDoc.EmailAddress").Trim();
                //System.Diagnostics.Process.Start("Outlook.exe" , "/c ipm.note /m " + strEmailAddressTo  +" /a \"" + pdfFile + "\"");   //Win XP ko hieu
                //MessageBox.Show("Outlook.exe /a \"" + pdfFile + "\"");
                System.Diagnostics.Process.Start("Outlook.exe"," /a \"" + pdfFile + "\""); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

       

        private void txtTuNgay_Validating(object sender, CancelEventArgs e)
        {
            if (intSoNgayDuocXem > 0)
            {
                try
                {
                    txtDenNgay.Text = txtTuNgay.getDateValue().Date.AddDays(intSoNgayDuocXem - 1).ToString("dd/MM/yyyy");
                    txtDenNgay.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ngày không hợp lệ");
                }
            }
        }

        
        private void cmdEmail_Click_1(object sender, EventArgs e)
        {
            pdfFile = _strReportFile.Replace(".rpt", ".pdf");
            if (pdfFile.IndexOf(".pdf") < 0) pdfFile = pdfFile + ".pdf";
            //MessageBox.Show(pdfFile);
            try
            {
                ExportOptions CrExportOptions;
                DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();
                CrDiskFileDestinationOptions.DiskFileName = pdfFile;
                CrExportOptions = rpt.ExportOptions;
                CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                CrExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
                CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                CrExportOptions.FormatOptions = CrFormatTypeOptions;
                rpt.Export();

                sendmail();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void txtMaLop_TextChanged(object sender, EventArgs e)
        {
            if (GlobalVariable.WSInfo.CompanyID.ToLower() == "school")
            {
                txtEnquiryNumber.Text = "";
                txtEnquiryNumber.RefField = "MaHocTap";
                txtEnquiryNumber.RefTable = " (SELECT top 200 MaHocTap, HoLot + ' ' + Ten as HoTen From HOCSINH_LOP " +
                                            "  join HOCSINH on HOCSINH_LOP.MaHocSinh = HOCSINH.MaHocSinh " +
                                            " where MaLop = '" + txtMaLop.Text + "' order by STT_SoCai )   as DM ";
            }
            else
            {
                txtEnquiryNumber.Text = "";
                txtEnquiryNumber.RefField = "EnquiryNumber";
                txtEnquiryNumber.RefTable = " (SELECT top 200 HOCTAP.EnquiryNumber, HoLot + ' ' + Ten as HoTen From HOCTAP " +
                                            " join Enquiry on HOCTAP.EnquiryNumber = Enquiry.EnquiryNumber " +
                                            " where MaLop = '" + txtMaLop.Text + "' order by Ten, HoLot )  as DM ";
            }

        }

       
    }
}
